package org.wejob.core.log;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.LinkedList;

public class MemoryRecords {
    long maxOffset;
    ByteBuffer buffer;
    LinkedList<Callback>callbacks;

    LinkedList<MessageRecord>records;

    public MemoryRecords(ByteBuffer byteBuffer,long maxoffset){
        this.buffer=byteBuffer;
        this.maxOffset=maxoffset;
        this.records=new LinkedList<>();
    }
    public boolean append(long offset,byte[] serializeMessage){
        int size=serializeMessage.length;
        if(serializeMessage.length<=buffer.limit()-buffer.position()){
            //System.out.println("append record--"+offset);
            buffer.put(serializeMessage);
            this.maxOffset= offset;
            return true;
        }
        return false;
    }

    public int writeTo(FileChannel channel) throws IOException {
        buffer.flip();
        buffer.mark();

        int written = 0;
        while (written < buffer.limit())
            written += channel.write(buffer);
        buffer.reset();
        return written;
    }

}
